package 剑指offer.第2天;

import java.util.Arrays;
import java.util.LinkedList;

/**
 * 剑指 Offer 06. 从尾到头打印链表
 输入一个链表的头节点，从尾到头反过来返回每个节点的值（用数组返回）。
 示例 1：
 输入：head = [1,3,2]
 输出：[2,3,1]
 */
class Solution {
    public int[] reversePrint1(ListNode head) {
        LinkedList<Integer> link = new LinkedList();
        while (head != null){
            link.push(head.val);
            head = head.next;
        }
        int size = link.size();
        int result[] = new int[size];
        for (int i = 0; i < size; i++) {
            result[i] = link.pop();
        }
        return result;
    }
    public int[] reversePrint(ListNode head) {
        ListNode node = head;
        int len = 0; // 计算链表长度
        while(node!=null){
            len++;
            node=node.next;
        }
        // 填充数组
        int[] res = new int[len];
        while(head!=null){
            res[--len] = head.val;
            head=head.next;
        }
        return res;
    }

    public static void main(String[] args) {
        ListNode node = new ListNode(1);
        node.next = new ListNode(3);
        node.next.next = new ListNode(2);

        int[] ints = new Solution().reversePrint(node);
        System.out.println("Arrays.toString(ints) = " + Arrays.toString(ints));
    }
}

class ListNode {
 int val;
 ListNode next;
 ListNode(int x) { val = x; }
}
